package engine;

import java.util.HashMap;
import java.util.Set;

public class BooleanOperator {

    BooleanOperator filsG, filsD;
    String operator;
    int VALEUR_P = 2;
    static private HashMap<String, Double> weights_file;
    static double denominateur;
    static Set<String> lsMots;

    public BooleanOperator(String lstToken) {
        operator = lstToken;
        filsG = filsD = null;
    }

    public void addChildLeft(BooleanOperator n) {
        if (filsG == null) {
            filsG = n;
        } else if (filsG.isLeaf()) {
            BooleanOperator b = filsG;

        } else {
        }
    }

    public void addChildRight(BooleanOperator n) {
        if (filsD == null) {
            filsD = n;
        } else if (filsD.isLeaf()) {
            BooleanOperator b = filsD;
            filsD = n;
            filsD.addChildLeft(b);

        } else {
            filsD.addChild(n);
        }
    }

    public void addChild(BooleanOperator n) {
        if (filsG == null) {
            addChildLeft(n);
        } else if (filsD == null) {
            addChildRight(n);
        } else {
            filsD.addChild(n);
        }
    }

    public boolean isLeaf() {

        return !operator.contains("AND") && !operator.contains("OR");
    }

    public double calculus() {
        double result = 0.0;
        if (isLeaf()) {
            if (weights_file.containsKey(operator)) {
                return weights_file.get(operator) / denominateur;
            }
        } else {
            switch (operator) {
                case "AND": // AND
                    result = 1.0 - Math.pow(((Math.pow(1.0 - filsG.calculus(), VALEUR_P) + Math.pow(1.0 - filsD.calculus(), VALEUR_P)) / 2), 1 / VALEUR_P);
                    break;
                case "OR":
                    result = Math.pow(((Math.pow(filsG.calculus(), VALEUR_P) + Math.pow(filsD.calculus(), VALEUR_P)) / 2), 1 / VALEUR_P);
                    break;
            }

        }
        return result;
    }

    public static void setQuery(Set<String> set) {
        lsMots = set;
    }

    public static void setData(HashMap<String, Double> weights2) {
        weights_file = weights2;
    }

    public static void setDenom(double d) {
        denominateur = d;
    }

    public String toString() {
        if (isLeaf()) {
            return operator;
        } else {
            return " ( [" + filsG.toString() + "]  " + operator + "  [" + filsD.toString() + "]  )";
        }
    }
}
